<template>
  <el-container>
    <el-main class="main-bg">
      <el-form ref="searchForm" :model="searchForm" label-width="80px">
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="库名称">
              <el-select v-model="searchForm.warehouseName" placeholder="请选择库名称" filterable clearable>
                <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商家名称">
              <el-select v-model="searchForm.businessName" placeholder="请选择商家" filterable clearable>
                <el-option v-for="item in selectOpt" :key="item.id" :label="item.businessName" :value="item.businessName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人">
              <el-input v-model="searchForm.contacts" placeholder="请输入联系人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式">
              <el-input v-model="searchForm.tel" placeholder="请输入联系人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24" class="text-right">
            <el-button icon="iconfont iconxianxing_sousuo" type="primary" @click="handleSearch">
              查询
            </el-button>
            <el-button icon="iconfont iconxianxing_zhongzhi" @click="handleReset">
              重置
            </el-button>
          </el-col>
          <el-col :span="24" class="text-left">
            <el-button type="primary" @click="onAdd">
              新增商家
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <Table
        ref="table"
        :current-page="page"
        :header-data="tableHeader"
        :index="false"
        :loading="loading"
        :page-size="limit"
        :table-data="tableData"
        border
        :total="total"
        class="data-table"
        style="width: 100%"
        @now-page="handlePage"
        @now-size="handleSize"
        @table-sort="handleSort"
      />
    </el-main>
    <el-drawer :title="title" :visible.sync="drawerVisible" :wrapper-closable="false">
      <div class="drawer-main">
        <el-form ref="form" :model="form" :rules="rules" label-position="top">
          <el-form-item label="商家名称" prop="businessName" required>
            <el-input v-model="form.businessName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属库" prop="warehouseId" required>
            <el-select v-model="form.warehouseId" placeholder="请选择" filterable clearable>
              <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
            </el-select>
          </el-form-item>
          <el-form-item label="所在地区" prop="provinceCode">
            <el-cascader v-model="form.selectedOptions" :options="options" style="width: 100%;" @change="handleChange" />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="form.contacts" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="联系方式" prop="tel">
            <el-input v-model="form.tel" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="法人登记证书" prop="url">
            <el-upload
              class="avatar-uploader"
              action="/api/business/upload"
              :show-file-list="false"
              :headers="headerToken"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.url" :src="form.url" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" placeholder="请输入" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <div v-if="type !== 'look'" class="drawer-footer">
        <div class="footer-btn">
          <el-button type="primary" @click="handleSubmit"> 确认</el-button>
          <el-button @click="onCancel"> 取消</el-button>
        </div>
      </div>
    </el-drawer>
    <viewer />
  </el-container>
</template>

<script>
import addTable from "@/mixins/addtable";
import { parseTime } from "@/utils";
import { codeToText } from "element-china-area-data";
import areaData from "@/utils/area-data";
import { postBusinessAdd, postBusinessUpdate, postBusinessDel, getBusinessList } from "./api";
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
import selectMinx from "../mixins/index";
export default {
  name: "WarehouseList",
  mixins: [addTable, selectMinx],
  data() {
    const validateTel = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入联系方式"));
      } else if (!reg.test(this.form.tel)) {
        callback(new Error("请输入有效的联系方式"));
      } else {
        callback();
      }
    };
    return {
      searchForm: {
        warehouseName: "",
        businessName: "",
        contacts: "",
        tel: "",
      },
      options: areaData.regionData,
      title: "",
      type: "look",
      tableHeader: [],
      drawerVisible: false,
      warehouseId: "",
      form: {
        selectedOptions: [],
        businessId: "",
        businessName: "",
        warehouseId: "",
        wearhouseName: "",
        address: "",
        provinceName: "",
        provinceCode: "",
        cityName: "",
        cityCode: "",
        districtName: "",
        districtCode: "",
        contacts: "",
        tel: "",
        url: "",
        remark: "",
      },
      warehouseList: [],
      selectOpt: [],
      rules: {
        warehouseId: [{ required: true, message: "库名称必填", trigger: "change" }],
        businessName: [{ required: true, message: "商家名称必填" }],
        // address: [
        //   { required: true, message: "详细地址必填", trigger: "change" },
        // ],
        // provinceCode: [
        //   { required: true, message: "省市区名称必填", trigger: "change" },
        // ],
        // contacts: [{ required: true, message: "联系人必填" }],
        // tel: [{ required: true, message: "联系方式必填" }],
        // url: [{ required: true, message: "法人登记证书必填" }],
      },
    };
  },
  computed: {
    headerToken() {
      return { authorization: getToken() };
    },
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.tableHeader = [
      {
        prop: "warehouseName",
        label: "所属库",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "businessName",
        label: "商家名称",
        sortable: false,
        overflow: true,
        align: "left",
        width: 200,
      },
      {
        prop: "contacts",
        label: "联系人",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "tel",
        label: "联系方式",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "provinceName",
        label: "所在省",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "cityName",
        label: "所在市",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "districtName",
        label: "所在区",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "address",
        label: "详细地址",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "url",
        label: "法人登记证书",
        sortable: false,
        overflow: false,
        align: "left",
        render: (h, vm) => {
          return vm.url ? (
            <el-button type="text" onClick={() => this.show(vm.url)}>
              查看大图
            </el-button>
          ) : (
            <span>未上传</span>
          );
        },
      },
      {
        prop: "remark",
        label: "备注",
        sortable: false,
        overflow: true,
        align: "left",
      },
      {
        prop: "createdTime",
        label: "创建时间",
        sortable: false,
        overflow: true,
        align: "left",
        width: 180,
        render: (h, vm) => {
          const time = vm.createdTime ? parseTime(vm.createdTime) : "";
          return <span>{time}</span>;
        },
      },
      {
        width: 120,
        label: "操作",
        align: "left",
        fixed: "right",
        buttonList: (row, index) => {
          const arr = [];
          const isAdmin = this.userInfo.role === "1";
          if (isAdmin) {
            arr.push(
              {
                text: "编辑",
                type: "text",
                event: this.onEdit,
              },
              {
                text: "删除",
                type: "text",
                event: this.onDelete,
              }
            );
          } else {
            arr.push({
              text: "编辑",
              type: "text",
              event: this.onEdit,
            });
          }
          return arr;
        },
      },
    ];
    this.getTableData();
  },

  methods: {
    show(url) {
      this.$viewerApi({
        images: [url],
      });
    },
    handleChange(value) {
      if (value && value.length > 0) {
        this.form.provinceName = codeToText[value[0]];
        this.form.provinceCode = value[0];
        this.form.cityName = codeToText[value[1]];
        this.form.cityCode = value[1];
        this.form.districtName = codeToText[value[2]] || "";
        this.form.districtCode = value[2] || "";
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.url = res.data;
      this.$forceUpdate();
    },
    beforeAvatarUpload(file) {
      const isLt4M = file.size / 1024 / 1024 < 2;
      if (!isLt4M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt4M;
    },
    onEdit(row) {
      this.form = {
        ...row,
      };
      this.form.selectedOptions = [this.form.provinceCode, this.form.cityCode, this.form.districtCode];
      this.type = "edit";
      this.title = "编辑库";
      this.drawerVisible = true;
    },
    onAdd() {
      this.form = {};
      this.type = "add";
      this.title = "新增库";
      this.drawerVisible = true;
    },
    onDelete(row) {
      this.$confirm("您确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        postBusinessDel({ businessId: row.businessId })
          .then(({ success, message }) => {
            if (success) {
              this.$message.success(message);
            } else {
              this.$message.error(message);
            }
            this.getTableData();
          })
          .catch();
      });
    },
    getTableData() {
      this.loading = true;
      this.getTableParams();
      getBusinessList(this.tableParams)
        .then((res) => {
          if (!res) return;
          const { data, pageInfo } = res;
          setTimeout(() => {
            this.loading = false;
            this.tableData = data;
            this.total = pageInfo.total;
          }, 500);
        })
        .catch((err) => {
          console.log("TCL: getTableData -> err", err);
        });
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.warehouseName = this.warehouseList
            .filter((item) => item.warehouseId === this.form.warehouseId)
            .map((item) => item.warehouseName)
            .join("");

          this.form.businessId
            ? postBusinessUpdate(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.onCancel();
                this.form = {};
                this.getTableData();
              })
            : postBusinessAdd(this.form).then(({ success, message }) => {
                if (success) {
                  this.$message.success(message);
                } else {
                  this.$message.error(message);
                }
                this.onCancel();
                this.form = {};
                this.getTableData();
              });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    onCancel() {
      this.drawerVisible = false;
      this.$refs.form.resetFields();
    },
  },
};
</script>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  line-height: 110px;
  text-align: center;
}
.avatar {
  width: 110px;
  height: 110px;
  display: block;
}
</style>
